import { defineStore } from 'pinia'
import exhibition from '../../api/exhibition'

export const useExhibitionOrderStore = defineStore('exhibitionOrder', {
    state: () => ({
        // 当前选中的展览信息
        currentExhibition: null,
        // 预约票数据
        ticketData: [],
        // 加载状态
        loading: false,
        // 总票数
        totalTickets: 0,
        // 默认每天票数
        defaultDailyTickets: 0,
        // 默认票价
        defaultTicketPrice: 0,
        //默认售出票数
        defaultSoldTickets: 0,

    }),

    actions: {
        // 重置状态
        resetState() {
            this.currentExhibition = null
            this.ticketData = []
            this.loading = false
            this.currentTicketType = 1
        },
        // 设置当前展览
        setCurrentExhibition(exhibition) {
            this.currentExhibition = exhibition
            // 初始化票数据
            this.initTicketData()
        },

        // 初始化票数据
        initTicketData() {
            this.loading = true

            try {
                if (!this.currentExhibition) {
                    this.ticketData = []
                    this.loading = false
                    return
                }

                // 计算展览持续天数
                const startDate = new Date(this.currentExhibition.startTime || new Date())

                // 处理 endTime 为 null 的情况
                let endDate
                let diffDays

                if (this.currentExhibition.endTime) {
                    // 如果有结束时间，正常计算持续天数
                    endDate = new Date(this.currentExhibition.endTime)
                    const diffTime = Math.abs(endDate - startDate)
                    diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1 // 包含开始和结束日
                } else {
                    // 如果没有结束时间（常设展览），默认设置为14天
                    endDate = new Date(startDate)
                    endDate.setDate(startDate.getDate() + 13) // 设置为14天（包括开始日）
                    diffDays = 14
                }

                // 获取预约数据，如果后端已有数据则使用后端数据，否则初始化
                this.getExhibitionTickets(this.currentExhibition.id).then(res => {
                    this.totalTickets = 0
                    if (res.data.code === 200 && res.data.data != null) {
                        this.ticketData = res.data.data
                        console.log('获取预约数据成功:', res.data.data)

                        // 如果后端返回了票价信息，更新票价类型
                        if (res.data.ticketTypes && res.data.ticketTypes.length > 0) {
                            this.ticketTypes = res.data.ticketTypes
                        } else if (res.data.defaultTicketPrice) {
                            // 如果只返回了默认票价，更新默认票价
                            this.defaultTicketPrice = res.data.defaultTicketPrice
                            this.updateTicketPrices(this.defaultTicketPrice)
                        }
                    } else {
                        // 初始化票数据
                        this.ticketData = []
                        let currentDate = new Date(startDate)

                        for (let i = 0; i < diffDays; i++) {
                            this.ticketData.push({
                                date: new Date(currentDate),
                                formattedDate: this.formatDate(currentDate),
                                availableTickets: this.defaultDailyTickets,
                                paidNumber: this.defaultSoldTickets,
                                isWeekend: [0, 6].includes(currentDate.getDay()),
                                isHoliday: false, // 可以通过API判断是否为节假日
                                ticketPrice: this.defaultTicketPrice // 添加默认票价
                            })

                            currentDate.setDate(currentDate.getDate() + 1)
                        }
                    }
                    this.loading = false
                }).catch(err => {
                    console.error('获取展览票数据失败:', err)
                    this.loading = false
                })
            } catch (error) {
                console.error('初始化票数据失败:', error)
                this.loading = false
            }
        },

        // 新增票数据
        newTicketData() {
            this.loading = true
            // 正确获取最后一天的日期
            const lastDate = this.ticketData.length > 0
                ? new Date(this.ticketData[this.ticketData.length - 1].date)
                : new Date()
            // 计算下一天（当前最后一天 + 1天）
            const nextDate = new Date(lastDate)
            nextDate.setDate(lastDate.getDate() + 1)
            const newTIcket = {
                date: new Date(nextDate),
                formattedDate: this.formatDate(nextDate),
                availableTickets: this.defaultDailyTickets,
                paidNumber: this.defaultSoldTickets,
                isWeekend: [0, 6].includes(nextDate.getDay()),
                isHoliday: false, // 可以通过API判断是否为节假日
                ticketPrice: this.defaultTicketPrice // 添加默认票价
            };
            try {
                this.ticketData = [...this.ticketData, newTIcket]
                console.log('新增票数据成功:', newTIcket)
            } finally {
                this.loading = false
            }
        },

        // 更新票价类型的价格
        updateTicketTypePrice(typeId, price) {
            const index = this.ticketTypes.findIndex(type => type.id === typeId)
            if (index !== -1) {
                this.ticketTypes[index].price = price

                // 如果是默认票价，更新所有票价
                if (this.ticketTypes[index].isDefault) {
                    this.defaultTicketPrice = price
                    // 更新其他票价类型的价格（根据折扣）
                    this.ticketTypes.forEach(type => {
                        if (!type.isDefault && type.discount) {
                            type.price = Math.round(this.defaultTicketPrice * type.discount)
                        }
                    })
                }
            }
        },

        // 根据默认票价更新所有票价
        updateTicketPrices(defaultPrice) {
            this.defaultTicketPrice = defaultPrice

        },

        // 设置当前选中的票价类型
        setCurrentTicketType(typeId) {
            this.currentTicketType = typeId
        },

        // 格式化日期
        formatDate(date) {
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
        },

        // 更新某天的票数
        updateDailyTickets(index, tickets) {
            if (index >= 0 && index < this.ticketData.length) {
                this.ticketData[index].availableTickets = tickets
            }
        },

        // 更新某天的票价
        updateDailyTicketPrice(index, price) {
            if (index >= 0 && index < this.ticketData.length) {
                this.ticketData[index].ticketPrice = price
            }
        },

        // 批量设置票数
        batchUpdateTickets(type, tickets) {
            switch (type) {
                case 'all':
                    // 设置所有日期
                    this.ticketData.forEach(item => {
                        item.availableTickets = tickets
                    })
                    break
                case 'weekday':
                    // 设置工作日
                    this.ticketData.forEach(item => {
                        if (!item.isWeekend && !item.isHoliday) {
                            item.availableTickets = tickets
                        }
                    })
                    break
                case 'weekend':
                    // 设置周末
                    this.ticketData.forEach(item => {
                        if (item.isWeekend) {
                            item.availableTickets = tickets
                        }
                    })
                    break
                case 'holiday':
                    // 设置节假日
                    this.ticketData.forEach(item => {
                        if (item.isHoliday) {
                            item.availableTickets = tickets
                        }
                    })
                    break
            }
        },

        // 批量设置票价
        batchUpdateTicketPrice(type, price) {
            switch (type) {
                case 'all':
                    // 设置所有日期
                    this.ticketData.forEach(item => {
                        item.ticketPrice = price
                    })
                    break
                case 'weekday':
                    // 设置工作日
                    this.ticketData.forEach(item => {
                        if (!item.isWeekend && !item.isHoliday) {
                            item.ticketPrice = price
                        }
                    })
                    break
                case 'weekend':
                    // 设置周末
                    this.ticketData.forEach(item => {
                        if (item.isWeekend) {
                            item.ticketPrice = price
                        }
                    })
                    break
                case 'holiday':
                    // 设置节假日
                    this.ticketData.forEach(item => {
                        if (item.isHoliday) {
                            item.ticketPrice = price
                        }
                    })
                    break
            }
        },

        // 保存票数据到后端
        async saveTicketData() {
            if (!this.currentExhibition || this.ticketData.length === 0) {
                return Promise.reject('没有可保存的数据')
            }

            // 获取原始数据用于对比
            const originalData = await this.getExhibitionTickets(this.currentExhibition.id)
            const originalTickets = originalData.data.code === 200 && originalData.data.data
                ? originalData.data.data
                : []

            // 创建映射表便于快速查找原始数据
            const originalMap = new Map()
            originalTickets.forEach(item => {
                originalMap.set(item.formattedDate, item)
            })

            const saveData = {
                exhibitionId: this.currentExhibition.id,
                tickets: this.ticketData
                    .filter(item => {
                        // 过滤条件：票数>0且(是新数据或与原始数据不同)
                        if (item.availableTickets <= 0) return false

                        const original = originalMap.get(item.formattedDate)
                        // 如果是新日期，或者数据有变化，则包含
                        return !original ||
                            original.availableTickets !== item.availableTickets ||
                            original.ticketPrice !== item.ticketPrice
                    })
                    .map(item => ({
                        date: item.formattedDate,
                        availableTickets: item.availableTickets,
                        paidNumber: item.paidNumber,
                        ticketPrice: item.ticketPrice || this.defaultTicketPrice
                    })),
                ticketTypes: this.ticketTypes
            }
            console.log('保存票数据:', saveData)

            // 调用API保存数据
            
            console.log('保存票数据:', saveData)
            await exhibition.releaseTicket(saveData).then(res => {
                if (res.data.code === 200) {
                    return Promise.resolve({ code: 200, message: '保存成功' })
                }
            }).catch(err => {
                console.error('保存票数据失败:', err)
                return Promise.reject('保存票数据失败')
            })
        },

        // 获取展览票数据
        async getExhibitionTickets(exhibitionId) {
            // 实际项目中应该调用API获取数据
            return exhibition.getTicketById(exhibitionId)
        },

        //获取票数变化
        //获取票数变化
        calculateTotalTickets() {
            // 先重置总票数为0
            this.totalTickets = 0
            // 然后累加所有日期的票数
            for (let i = 0; i < this.ticketData.length; i++) {
                this.totalTickets = this.totalTickets + this.ticketData[i].availableTickets
            }
        },
        changeLoading() {
            this.loading = !this.loading
            setTimeout(() => {
                this.loading = !this.loading
            }, 500);
        },
    }
})
